package com.jlastu.znb.dfh;


import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.jlastu.znb.database.DBHelper;
import com.jlastu.znb.utils.SpUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class dfhManager {
    private DBHelper dbHelper;
    private Context context;
    private SpUtils mSpUtils;
    private static dfhManager instance;
    private List<dfhItem> dfhItems;

    public dfhManager(Context context) {
        this.context = context;
        this.dbHelper = new DBHelper(context);
        this.mSpUtils = new SpUtils(context); // 初始化SpUtils
    }
    public void addTodfh(int goodsId, int quantity, int userId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("goods_id", goodsId);
        values.put("quantity", quantity); // 初始化数量
        values.put("user_id", userId);

        // 检查购物车中是否已有该商品
        String[] columns = { "quantity" };
        String selection = "goods_id=? AND user_id=?";
        String[] selectionArgs = { String.valueOf(goodsId), String.valueOf(userId) };
        Cursor cursor = db.query("dfh", columns, selection, selectionArgs, null, null, null);

        if (cursor.moveToFirst()) {
            // 如果存在，更新数量
            int currentQuantity = cursor.getInt(0);
            quantity += currentQuantity; // 增加现有数量
            values.put("quantity", quantity); // 更新ContentValues中的数量
            String whereClause = "goods_id=? AND user_id=?";
            String[] whereArgs = { String.valueOf(goodsId), String.valueOf(userId) };
            db.update("dfh", values, whereClause, whereArgs);
        } else {
            // 如果不存在，插入新记录
            db.insert("dfh", null, values);
        }
        cursor.close();
    }

    @SuppressLint("Range")
    public List<dfhItem> getdfhItems() {
        List<dfhItem> dfhItems = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        // SQL查询，关联商品表和购物车表
        String query = "SELECT dfh.*, goods.goods_name, goods.goods_price, photo.image " +
                "FROM dfh " +
                "JOIN goods ON dfh.goods_id = goods._id " +
                "LEFT JOIN photo ON goods._id = photo.goods_id " +
                "WHERE dfh.user_id = ?";
        String[] args = { String.valueOf(getUserId()) };
        Cursor cursor = db.rawQuery(query, args);
        if (cursor.moveToFirst()) {
            do {
                dfhItem dfhItem = new dfhItem();
                // 填充dfhItem对象
                dfhItem.setId(cursor.getInt(cursor.getColumnIndex("_id")));
                dfhItem.setGoodsId(cursor.getInt(cursor.getColumnIndex("goods_id")));
                dfhItem.setGoodsName(cursor.getString(cursor.getColumnIndex("goods_name")));
                dfhItem.setGoodsPrice(cursor.getDouble(cursor.getColumnIndex("goods_price")));
                dfhItem.setQuantity(cursor.getInt(cursor.getColumnIndex("quantity")));
                // 获取图片数据
                byte[] imageBytes = cursor.getBlob(cursor.getColumnIndex("image"));
                // 将字节数据转换为Bitmap（这里需要在适配器中处理）
                dfhItem.setImageBytes(imageBytes);
                dfhItems.add(dfhItem);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return dfhItems.stream().filter(dfhItem::hasImage).collect(Collectors.toList());
    }

    // 从待收货中删除指定的商品项
    public void removeFromdfh(int dfhItemId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("dfh", "_id = ?", new String[]{String.valueOf(dfhItemId)});
    }

    // 辅助方法，获取当前登录用户的ID
    private int getUserId() {
        return mSpUtils.getInt(SpUtils.LOGIN_KEY, -1); // 使用spUtils而不是new SpUtils(this)
    }
//    /**
//     * 更新购物车中商品的数量
//     *
//     * @param dfhItemId 购物车项的ID
//     * @param newQuantity 新的商品数量
//     */
//    public void updateQuantity(int dfhItemId, int newQuantity) {
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        ContentValues values = new ContentValues();
//        values.put("quantity", newQuantity); // 更新数量字段
//
//        // 构建更新条件，这里假设_id是购物车表的主键
//        String whereClause = "_id = ?";
//        String[] whereArgs = {String.valueOf(dfhItemId)};
//
//        // 执行更新操作
//        int rowsUpdated = db.update("dfh", values, whereClause, whereArgs);
//
//        if (rowsUpdated == 0) {
//            // 如果没有行被更新，可能指定的ID不存在
//            Log.e("dfhManager", "No dfh item found with ID: " + dfhItemId);
//        }
//    }

}
